<template>
    <div class="list-wrapper">
        <Block>
            <DataGrid
                :auto-load="autoLoad"
                row-key="id"
                border
                ref="dataGridRef"
                @selection-change="handleSelectionChange"
                showSelection
            >
                <template #toolbar-search>
                    <div class="query-from-box">
                        <el-form>
                            <el-form-item>
                                <el-input v-model="queryData.jobInfoKey" placeholder="任务名称/标识符" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-input v-model="queryData.productKey" placeholder="产品名称/标识符" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-select v-model="queryData.triggerType" placeholder="触发方式" clearable>
                                    <el-option
                                        v-for="(value, key) in TriggerType"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-select placeholder="状态" v-model="queryData.state" clearable>
                                    <el-option
                                        v-for="(value, key) in ProductState"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #toolbar-operation>
                    <el-button
                        type="primary"
                        @click="onBatchEnableJob"
                        :disabled="!(enabledTableSelectId && enabledTableSelectId.length)"
                        >启用</el-button
                    >
                </template>
                <el-table-column type="index" label="序号" width="60" align="center" fixed />
                <el-table-column label="任务名称" width="300" fixed show-overflow-tooltip>
                    <template #default="scope">
                        <el-button link type="primary" @click="onGoDetail(scope.row)">
                            {{ scope.row.jobName }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="jobNo" label="标识符" show-overflow-tooltip />
                <el-table-column prop="productName" label="产品" show-overflow-tooltip />
                <el-table-column label="触发方式">
                    <template #default="scope">
                        {{ TriggerType[scope.row.triggerType] }}
                    </template>
                </el-table-column>
                <el-table-column prop="jobDesc" label="任务描述" show-overflow-tooltip />
                <el-table-column prop="state" label="状态">
                    <template #default="scope">
                        <span class="table-item-status" :status="ProductState[scope.row.state]">
                            {{ ProductState[scope.row.state] }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="90" fixed="right">
                    <template #default="scope">
                        <template v-if="scope.row.state == 'DISABLED'">
                            <el-button link type="primary" @click="onSetJob(scope.row)"> 设置 </el-button>
                            <el-button link type="primary" @click="onEnable(scope.row)"> 启用 </el-button>
                        </template>
                        <el-button v-else link type="primary" @click="onDisable(scope.row)"> 停用 </el-button>
                    </template>
                </el-table-column>
            </DataGrid>
        </Block>
    </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { IoTTaskService } from '@great/services';
import { showPopupBox } from '@great/utils';
import { useRouter } from 'vue-router';
import { ProductState, TriggerType } from '@/utils/constant';
import { DataGrid, Block, type DataGridInstance } from '@great/components';
import SetModal from './components/list/SetModal.vue';
import { checkPermi } from '@/utils/ruoyi';

const router = useRouter();

// 查询条件
const queryData = ref({
    productKey: '',
    jobInfoKey: '',
    triggerType: '',
    state: ''
});
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');

const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await IoTTaskService.getPageJob({
            current,
            size,
            ...queryData.value
        });
        return { data: res.data.records, total: res.data.total };
    }
});
// 表格勾选数据
const tableSelect = ref<unknown[]>([]);
const enabledTableSelectId = ref<string[]>([]);
// 表格勾选
const handleSelectionChange = (val: unknown[]) => {
    tableSelect.value = val;
    enabledTableSelectId.value = [];
    val.forEach((item: any) => {
        if (item.state == 'DISABLED') {
            enabledTableSelectId.value.push(item.jobNo);
        }
    });
};

// 设置任务
const onSetJob = row => {
    showPopupBox(SetModal, {
        row: row,
        callBack: dataGridRef.value?.refresh
    });
};

// 查看详情
const onGoDetail = (row: { jobNo: string }) => {
    if (checkPermi(['iot:task:detail'])) {
        router.push({
            name: 'IoT-task-detail',
            params: {
                id: row?.jobNo
            }
        });
    }
};
// 停用
const onDisable = async (row: { jobNo: string; jobName: string }) => {
    ElMessageBox.confirm(`确认停用任务 ${row.jobName} ？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await IoTTaskService.disableJob(row.jobNo);
            ElNotification({
                title: '停用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 批量启用
const onBatchEnableJob = () => {
    ElMessageBox.confirm(`确认批量启用任务？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await IoTTaskService.batchEnableJob(enabledTableSelectId.value);
            ElNotification({
                title: '批量启用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 启用
const onEnable = async (row: { jobNo: string; jobName: string }) => {
    const res = await IoTTaskService.enableJobCheck([row.jobNo]);
    if (res.data && res.data.canEnable) {
        ElMessageBox.confirm(`确认启用任务 ${row.jobName} ？`, '提示', {
            type: 'warning'
        }).then(async () => {
            await IoTTaskService.enableJob(row?.jobNo);
            ElNotification({
                title: '启用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        });
    } else {
        for (let key in res.data.msg) {
            ElMessageBox.confirm(`${res.data.msg[`${key}`]}`, '提示', {
                showCancelButton: false,
                type: 'warning'
            });
        }
    }
};
</script>
<style scoped lang="scss">
.list-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-tag {
            display: flex;
        }
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
                background-color: #e6a23c;
            }
        }
        .table-item-status[status='停用'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='启用'] {
            &::before {
                background-color: #67c23a;
            }
        }
    }
}
</style>
